package com.neuedu.funlifebbs.controller;

import java.io.IOException;
import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.PageInfo;
import com.neuedu.funlifebbs.bean.Notices;
import com.neuedu.funlifebbs.query.NoticesQuery;
import com.neuedu.funlifebbs.service.NoticesService;
import com.neuedu.funlifebbs.utils.JsonModel;

/**
 *
 * @author hw
 * @version 2019年8月19日下午2:54:03
 *
 */
@Controller
@RequestMapping("admin/notices")
public class NoticesController {

	@Autowired
	NoticesService noticesService;

	/**
	 * 转发到公告列表页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/listUI", method = RequestMethod.GET)
	public String listUi() {
		return "back/notices/list";
	}

	/**
	 * 分页查询并显示在公告列表页面
	 * 
	 * @param noticesQuery
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value = "/list", method = RequestMethod.GET)
	@ResponseBody
	public JsonModel list(NoticesQuery noticesQuery) throws IOException {
		PageInfo<Notices> pageInfo = noticesService.query(noticesQuery);
		JsonModel jsonModel = new JsonModel();
		jsonModel.setMsg("查找成功");
		jsonModel.setSuccess(true);
		jsonModel.setTotal(pageInfo.getTotal());
		jsonModel.setRows(pageInfo.getList());
		return jsonModel;
	}

	/**
	 * 转发到添加公告页面
	 * 
	 * @return
	 */
	@RequestMapping(value = "/addUI", method = RequestMethod.GET)
	public String addUi() {
		return "back/notices/add";
	}

	/**
	 * 添加新公告
	 * 
	 * @param notices
	 * @return
	 */
	@RequestMapping(value = "/add", method = RequestMethod.POST)
	public String add(Notices notices) {
		Date date = new Date();
		notices.setNoticetime(date);
		if (notices.getId() != 0) {
			noticesService.update(notices);
		} else {
			noticesService.add(notices);
		}
		return "redirect:/admin/notices/listUI";
	}

	/**
	 * 根据公告id修改公告
	 * 
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/edit/{id}", method = RequestMethod.GET)
	public String editUi(Model model, @PathVariable int id) {
		Notices notices = noticesService.findById(id);
		model.addAttribute("notices", notices);
		return "back/notice/edit";
	}

	/**
	 * 根据公告id删除公告
	 * 
	 * @param id
	 * @return
	 */
	@RequestMapping(value = "/delete/{id}", method = RequestMethod.GET)
	@ResponseBody
	public JsonModel delete(@PathVariable int id) {
		noticesService.deleteById(id);
		JsonModel jsonModel = new JsonModel();
		jsonModel.setSuccess(true);
		jsonModel.setMsg("删除成功");
		return jsonModel;
	}
}
